<!-- 收到的评论和@ -->
<template>
    <MessageList 
        title="收到的评论和@"
        :messageList="messageList"
        :unreadCount="unreadCount"
        @item-click="handleItemClick"
    />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import MessageList from '@/components/MessageList.vue';

const router = useRouter();
const messageList = ref([]);
const unreadCount = ref(0);

// 从本地存储加载已读状态
const loadReadStatus = () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return {};
        
        const readStatus = localStorage.getItem(`commentReadStatus_${userId}`) || '{}';
        return JSON.parse(readStatus);
    } catch (error) {
        console.error('加载评论已读状态失败:', error);
        return {};
    }
};

// 保存已读状态到本地存储
const saveReadStatus = (readStatus) => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return;
        
        localStorage.setItem(`commentReadStatus_${userId}`, JSON.stringify(readStatus));
    } catch (error) {
        console.error('保存评论已读状态失败:', error);
    }
};

// 标记消息为已读
const markAsRead = (messageId) => {
    const readStatus = loadReadStatus();
    readStatus[messageId] = true;
    saveReadStatus(readStatus);
    
    // 更新消息列表中的已读状态
    const message = messageList.value.find(msg => msg.id === messageId);
    if (message) {
        message.isRead = true;
    }
    
    // 重新计算未读数量
    calculateUnreadCount();
};

// 计算未读消息数量
const calculateUnreadCount = () => {
    const readStatus = loadReadStatus();
    unreadCount.value = messageList.value.filter(msg => !readStatus[msg.id]).length;
    
    // 保存未读数量到localStorage，供News页面使用
    try {
        const userId = localStorage.getItem('user_id');
        if (userId) {
            localStorage.setItem(`commentUnreadCount_${userId}`, unreadCount.value.toString());
        }
    } catch (error) {
        console.error('保存评论未读数量失败:', error);
    }
};

// 生成消息唯一ID
const generateMessageId = (noteId, commentId) => {
    return `comment_${noteId}_${commentId}`;
};

// 格式化时间
const formatTime = (timeStr) => {
    if (!timeStr) return '';
    
    const now = new Date();
    const time = new Date(timeStr);
    
    // 检查时间是否有效
    if (isNaN(time.getTime())) {
        console.error('Invalid time string:', timeStr);
        return '';
    }
    
    // 给时间加上8小时
    time.setHours(time.getHours() + 8);
    
    const diff = now - time; // 时间差（毫秒）
    
    // 十分钟内
    if (diff < 10 * 60 * 1000) {
        return '刚刚';
    }
    
    // 24小时内
    if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const minutes = Math.floor(diff / (60 * 1000));
        
        if (hours === 0) {
            return `${minutes}分钟前`;
        } else {
            return `${hours}小时前`;
        }
    }
    
    // 本年内
    if (time.getFullYear() === now.getFullYear()) {
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${month}-${day}`;
    }
    
    // 超过本年
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 处理文本溢出
const truncateText = (text, maxLength = 50) => {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
};

// 获取用户的所有笔记
const fetchUserNotes = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('用户ID不存在');
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/users/${userId}/notes`);
        if (response.data.success) {
            const notes = response.data.data;
            console.log('获取到用户笔记:', notes);
            
            // 为每个笔记获取评论
            await fetchCommentsForNotes(notes);
        } else {
            console.error('获取用户笔记失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取用户笔记出错:', error);
    }
};

// 获取笔记的评论
const fetchCommentsForNotes = async (notes) => {
    try {
        const allComments = [];
        const readStatus = loadReadStatus();
        
        for (const note of notes) {
            try {
                const response = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/comments`);
                if (response.data.success) {
                    const comments = response.data.data;
                    console.log(`笔记 ${note.note_id} 的评论:`, comments);
                    
                    // 为每个评论获取用户信息
                    for (const comment of comments) {
                        try {
                            const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${comment.user_id}`);
                            if (userResponse.data.success) {
                                const userData = userResponse.data.data;
                                console.log(`评论用户 ${comment.user_id} 的详细信息:`, userData);
                                
                                const messageId = generateMessageId(note.note_id, comment.comment_id);
                                const commentMessage = {
                                    id: messageId,
                                    noteId: note.note_id,
                                    commentId: comment.comment_id,
                                    img: userData.avatar_url || '',
                                    title: userData.nickname || '未设置昵称',
                                    content: truncateText(comment.content),
                                    fullContent: comment.content, // 保存完整内容
                                    time: formatTime(comment.time),
                                    userId: localStorage.getItem('user_id'),
                                    isRead: readStatus[messageId] || false
                                };
                                
                                allComments.push(commentMessage);
                            }
                        } catch (error) {
                            console.error(`获取评论用户 ${comment.user_id} 信息失败:`, error);
                        }
                    }
                }
            } catch (error) {
                console.error(`获取笔记 ${note.note_id} 评论失败:`, error);
            }
        }
        
        // 按时间排序，最新的在前面
        allComments.sort((a, b) => new Date(b.time) - new Date(a.time));
        
        messageList.value = allComments;
        calculateUnreadCount();
        console.log('最终评论消息列表:', messageList.value);
        console.log('未读评论消息数量:', unreadCount.value);
    } catch (error) {
        console.error('获取评论列表出错:', error);
    }
};

// 处理点击事件
const handleItemClick = (item) => {
    console.log('点击了评论消息项:', item);
    
    // 标记消息为已读
    markAsRead(item.id);
    
    // 跳转到笔记详情页面
    router.push({
        name: 'mecont',
        query: {
            noteId: item.noteId,
            userId: item.userId
        }
    });
};

onMounted(() => {
    fetchUserNotes();
});
</script>
